package common

import (
	"chitchat_http/server"
	"fmt"
	"github.com/doujunyu/gogo/gogo_log"
	"github.com/doujunyu/gogo/job"
	"path"
	"strconv"

	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"time"
)

// CrossDomain 跨域
func CrossDomain(j *job.Job) {
	//j.W.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	//j.W.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
	//j.W.Header().Set("content-type", "application/json")             //返回数据格式是json

	j.W.Header().Set("Access-Control-Allow-Origin", "*") //域名请求
	j.W.Header().Add("Access-Control-Allow-Credentials", "true")
	j.W.Header().Add("Access-Control-Allow-Headers", "*")
	j.W.Header().Add("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS") //
	j.W.Header().Add("Access-Control-Allow-Headers", "Content-Type")                //
	j.W.Header().Set("content-type", "application/json")                            //返回数据格式是json
}

// TokenInput token获取
func TokenInput(j *job.Job) {
	j.GroupData["token"] = ""
	//获取token
	if j.R.Header["Token"] != nil && j.R.Header["Token"][0] != "" {
		j.GroupData["token"] = j.R.Header["Token"][0]
		return
	}
	if j.Input["token"] != "" {
		j.GroupData["token"] = j.Input["token"]
	}
}

// ByPublic 公共图片
func ByPublic(j *job.Job) {

	urlPath := j.R.URL.Path
	baseName:=path.Base(urlPath)   // 输出 name.html
	ext := path.Ext(baseName) // 输出 .html
	switch ext {
	case ".png":
		j.W.Header().Set("Content-Type", "image/png")
	case ".mp3":
		j.W.Header().Set("Content-Type", "audio/mp3")
	default:
		j.W.Header().Set("Content-Type", "image/png")
	}
	file, err := os.Open("." + urlPath)
	defer file.Close()
	if err != nil && os.IsNotExist(err) {
		fmt.Fprintln(j.W, "File not exist")
		return
	}
	fi,_ := file.Stat()//直接获取文件信息，文件信息中有文件长度
	j.W.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))
	buff, _ := ioutil.ReadAll(file)
	_, _ = j.W.Write(buff)
}

// ByDownLoad 文件下载
func ByDownLoad(j *job.Job) {
	gogo_log.Write("downlod", "下载文件"+j.R.URL.Path, "")
	j.W.Header().Set("Content-type", "application/force-download")
	j.W.Header().Set("Content-type", "application/octet-stream")
	j.W.Header().Set("Content-disposition", "attachment;filename="+j.R.URL.Path)
	file := "." + j.R.URL.Path
	f, err := os.Open(file)
	defer f.Close()
	if err != nil && os.IsNotExist(err) {
		fmt.Fprintln(j.W, "File not exist")
		return
	}
	http.ServeFile(j.W, j.R, file)
	return
}

// ByPictureUpLoading 图片上传
func ByPictureUpLoading(j *job.Job) {
	files := make(map[string]interface{})
	files["size"] = int64(1024 * 1024 * 5)
	files["name"] = time.Now().Format("2006-01-02-15-04-05") + fmt.Sprintf("%v", rand.Intn(10000))
	files["suffix"] = "png,jpg,jpeg,gif,webp,jfif"
	filePath := "common"
	if j.Input["path"] != "" {
		filePath = j.Input["path"]
	}
	file, err := j.InputFile("file", filePath, files)
	if err != nil {
		j.JsonError(nil, err.Error())
		return
	}
	j.JsonSuccess(os.Getenv("SERVER_HTTP") + file, "上传成功")
}

// CheckToken 登录检查
func CheckToken(j *job.Job) {
	if j.GroupData["token"] == nil {
		j.JsonError(nil, "请先登录", 2)
		return
	}
	//验证token
	token := j.GroupData["token"].(string)
	tokenData, err := server.TokenByGetToken(&token)
	if err != nil {
		j.JsonError(nil, "登录状态已过期", 2)
		return
	}
	j.GroupData["user_id"] = tokenData.UserId
	j.GroupData["is_admin"] = tokenData.IsAdmin
}
